package com.demo.config;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.fastjson.JSON;
import com.demo.dto.ExcelReportDto;
import com.demo.service.ReportService;
import lombok.extern.slf4j.Slf4j;


import java.util.Map;

/**
 * Excel导入监听器
 */
@Slf4j
public class DataListener implements ReadListener<ExcelReportDto> {
    private ReportService reportService;
    private TaskPoolConfig executor;

    public DataListener(ReportService reportService, TaskPoolConfig executor) {
        this.reportService = reportService;
        this.executor = executor;
    }

    @Override
    public void onException(Exception exception, AnalysisContext context) throws Exception {
        log.error("解析有异常！");
    }

    /**
     * 解析表头
     *
     * @param headMap
     * @param context
     */
    @Override
    public void invokeHead(Map<Integer, ReadCellData<?>> headMap, AnalysisContext context) {
        log.info("解析表头:{}", JSON.toJSONString(headMap));
    }

    /**
     * 这个每一条数据解析都会来调用
     *
     * @param data
     * @param analysisContext
     */
    @Override
    public void invoke(ExcelReportDto data, AnalysisContext analysisContext) {
        log.info("解析完一条！");
        //多线程处理加快速度
        executor.taskExecutor().execute(new Runnable() {
            @Override
            public void run() {
                reportService.handleOneExcelReportData(data);
            }
        });
    }

    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param analysisContext
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        log.info("解析完成！");
    }
}